package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.AddressDao;
import com.seadragon.app.ksr.model.Address;
import com.seadragon.app.ksr.model.Business;

@Repository("addressDao")
public class AddressDaoJpaImpl extends AbstractJpaDao implements AddressDao {

	@Override
	public Address findById(long id) {
		return entityManager.find(Address.class, id);
	}

	@Override
	public List<Address> findAll(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Address> cq = cb.createQuery(Address.class);
		Root<Address> root = cq.from(Address.class);
		cq.select(root);
		TypedQuery<Address> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

	@Override
	public List<Address> findAllUngeocodedAddresses(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Address> cq = cb.createQuery(Address.class);
		Root<Address> root = cq.from(Address.class);
		cq.select(root);
		cq.where(cb.equal(root.get("valid"), true));
		TypedQuery<Address> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

	@Override
	public boolean exists(String completeAddress) {
		Address address= findByCompleteAddress(completeAddress);
		return (address==null)?false:true;
	}
	
	@Override
	public Address findByCompleteAddress(String completeAddress){
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Address> cq = cb.createQuery(Address.class);
		Root<Address> root = cq.from(Address.class);
		cq.select(root);
		cq.where(cb.equal(root.get("completeAddress"), completeAddress));
		List<Address> addresses = entityManager.createQuery(cq).getResultList();
		if(addresses == null || addresses.size() == 0) return null;
		return addresses.get(0);
	}

	@Override
	public void save(Address address) {
		entityManager.persist(address);
	}

	@Override
	public void update(Address address) {
		entityManager.merge(address);
	}

}
